import {
  wxLogin,
  authUser,
  authUserSilence
} from '../../api/login';
import {
  setToken
} from '../../utils/storage';
import {
  showWxToast,
  getRandom,
  showWxLoading,
  hideWxLoading
} from '../../utils/index';
import qiniu from '../../utils/qiniu/index';
import defaultContent from '../../assets/constant/default';

const app = getApp();
const DEFAULTAVATAR = 'https://ustatic.hudongmiao.com/joymewMp/grayAvator.png';
// let btnLock = false;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    dialogVisible: {
      value: false,
      type: Boolean
    },
    liveId: {
      value: '',
      type: String
    }
  },
  observers: {
    'dialogVisible': function (dialogVisible) {
      if (dialogVisible) {
        // 授权的登录弹窗出现
        this.loginSilence();
      }
    },
    avatarCropped: function (newVal) {
      if (newVal) {
        this.setData({
          avatarUrl: newVal,
        });
        console.log('上传服务器前的图片地址:', this.data.avatarUrl);
        this.uploadAvatar(this.data.avatarUrl);
      }
    },
  },
  data: {
    isNewAuthBox: false,
    avatarUrl: DEFAULTAVATAR,
    avatarUncropped: '',
    avatarCropped: '',
    nickName: '',
    code: '',
    isUploading: false,
  },
  attached() {},
  /**
   * 组件的方法列表
   */
  methods: {
    loginSilence: function () {
      wxLogin()
        .then(res => {
          console.log('***wxLogin***');
          console.log(res);
          return authUserSilence(res.code);
        })
        .then(res2 => {
          console.log('***静默授权结果***');
          console.log(res2);
          setToken(res2.data.token);
          const tmpUserInfo = res2.data.user;
          // 增加校验 如果是默认头像、wxfile头像或者名字为空 需要用户重新授权
          if (tmpUserInfo.avator && tmpUserInfo.wx_name && !tmpUserInfo.avator.includes('defaultHeadImg') && !tmpUserInfo.avator.startsWith('wxfile://')) {
            app.setUserInfo({
              nickName: tmpUserInfo.wx_name,
              avatarUrl: tmpUserInfo.avator,
            });
            this.triggerEvent('authSuccess');
          } else {
            this.initQiniuInfo();
            this.setData({
              isNewAuthBox: true,
            });
          }
        })
        .catch(err => {
          console.log('静默授权失败');
          this.closeAuth();
        });
    },
    openAuthNew: function () {
      let that = this;
      if (this.data.isUploading) {
        showWxToast('头像上传中,请稍后...');
        return;
      }
      if (this.data.avatarUrl.startsWith('wxfile://')) {
        showWxToast('请等待头像上传完成');
        return;
      }
      if (!this.data.avatarUrl || this.data.avatarUrl === DEFAULTAVATAR) {
        wx.showModal({
          title: '提示',
          content: '请上传头像!',
          cancelText: '默认头像',
          confirmText: '知道了',
          success: function (sm) {
            if (sm.confirm) {
              console.log('用户点击确认');
            } else if (sm.cancel) {
              // 设置默认头像
              const AVATARS = defaultContent.defaultAvatars;
              const tmpLen = AVATARS.length;
              that.setData({
                avatarUrl: AVATARS[getRandom(0, tmpLen)],
              });
            }
          },
        });
        return;
      }
      if (!this.data.nickName) {
        // showWxToast('请填写姓名!');
        wx.showModal({
          title: '提示',
          content: '请填写姓名!',
          cancelText: '默认姓名',
          confirmText: '知道了',
          success: function (sm) {
            if (sm.confirm) {
              console.log('用户点击取消');
            } else if (sm.cancel) {
              // 设置默认姓名
              that.setData({
                nickName: `默认用户${getRandom(0, 9999)}`,
              });
            }
          },
        });
        return;
      }
      const tmpUserInfo = {
        nickName: this.data.nickName,
        avatarUrl: this.data.avatarUrl,
      };
      console.log('Roo-debug: 准备保存的用户信息', tmpUserInfo);
      app.setUserInfo(tmpUserInfo);
      this.triggerEvent('authSuccess');
    },
    closeAuth: function () {
      this.triggerEvent('authFail');
    },
    onChooseAvatar: function (e) {
      const {
        avatarUrl
      } = e.detail;
      console.log('Roo-debug: onChooseAvatar 获取到临时头像路径', avatarUrl);
      this.setData({
        avatarUrl,
        avatarUncropped: avatarUrl,
      });
      //  this.setData({
      //   avatarUrl,
      // });
    },
    handleCancelCropper() {
      this.setData({
        avatarUncropped: '',
        avatarUrl: '',
      });
    },
    handleConfirmCropper(e) {
      console.log('Roo-debug: 用户确认裁剪');
      this.setData({
        avatarUncropped: '',
        avatarCropped: e.detail,
      });
    },
    userNameBlur: function (e) {
      if (wx.requirePrivacyAuthorize) {
        wx.requirePrivacyAuthorize({});
      }
      this.setData({
        nickName: e.detail.value,
      });
    },
    uploadAvatar: function (avatarPath) {
      console.log('Roo-debug: 开始上传头像', avatarPath);
      showWxLoading('头像上传中...');
      this.setData({
        isUploading: true,
      });
      qiniu
        .qiniuUpload(avatarPath)
        .then(res => {
          console.log('Roo-debug: 头像上传成功', res);
          this.setData({
            avatarUrl: res.imageURL,
            isUploading: false,
          });
          hideWxLoading();
        })
        .catch(err => {
          console.log(err);
          this.setData({
            isUploading: false,
          });
          hideWxLoading();
          showWxToast('头像上传失败!请重新进入小程序!');
        });
    },
    initQiniuInfo: function () {
      qiniu
        .getQiniuToken()
        .then(res => {
          console.log(res.data.token);
          qiniu.initQiniu(res.data.token);
        })
        .catch(err => {
          console.log(err);
        });
    },
  }
})